/**
 * @param {number[][]} graph
 * @return {number[]}
 */
var eventualSafeNodes = function (graph) {

  function dfs(index) {
    if(arr[index]) {
      return arr[index] == 2;
    }
    arr[index] = 1;
    for(let i = 0; i < graph[index].length; i++) {
      if(!dfs(graph[index][i])) {
        return false;
      }
    }
    arr[index] = 2;
    return true;
  }
  // arr中，记录每一个节点的值，0代表没有访问过，1代表访问过，2代表为安全节点。
  let arr = new Array(graph.length).fill(0), result = [];
  for(let i = 0; i < graph.length; i++) {
    if(dfs(i)) {
      result.push(i);
    }
  }
  return result;
};
let graph = [
  [1, 2],
  [2, 3],
  [5],
  [0],
  [5],
  [],
  []
];
console.log(eventualSafeNodes(graph));
graph = [
  [1, 2, 3, 4],
  [1, 2],
  [3, 4],
  [0, 4],
  []
];
console.log(eventualSafeNodes(graph));
